<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>

<body>
  <h1>取消请求</h1>
  <input type="text" id="ipt">
  <button id="btn">点击获取数据</button>
  <button id="btn2">取消发送请求</button>
  <script>
    // 创建axios实例
    const myAxios = axios.create({
      baseURL: '/',
      timeout: 10000,
      header: {}
    })

    // 获取元素
    const obtn = document.getElementById('btn')
    const obtn2 = document.getElementById('btn2')
    const oipt = document.getElementById('ipt')
    const CancelToken = axios.CancelToken
    let cancel = null

    // 绑定点击事件
    obtn.onclick = async function () {
      // 获取文本框内容
      const iptValue = ipt.value

      try {
        const result = await myAxios.get('/userLazy', {
          params: {
            userId: iptValue
          },
          cancelToken: new CancelToken((c) => {
            cancel = c
          })
        })
        console.log(result.data);
      } catch (e) {
        console.log(e.message);
      }
    }

    // 取消请求点击事件
    obtn2.onclick = function () {
      cancel()
    }
  </script>
</body>

</html>